﻿using System;
using System.Reflection;
using Autofac.Application;
using Autofac.Core;

namespace Autofac
{
    internal class Program
    {
        private static IContainer _container;
        //private static IOutput output;
        private static void Main(string[] args)
        {
            //InitContainer();
            //_container.Resolve<DatabaseManager>().Search("SELECT * FORM USER");

            //官方文档参考测试 潘帅阳2019年1月23日15:06:09
            //DemoAppInitContainer();

            //不用Autofac的写法 潘帅阳 2019年1月23日16:34:23
            ConsoleOutput output = new ConsoleOutput();
            TodayWriter todayWriter = new TodayWriter(output);
            todayWriter.WriteDate();

            Console.ReadKey();
        }

        private static void InitContainer()
        {
            var assembly = Assembly.GetExecutingAssembly();

            var builder = new ContainerBuilder();
            builder.RegisterAssemblyTypes(assembly).AsSelf().AsImplementedInterfaces();

            builder.RegisterType<DatabaseManager>();
            builder.RegisterType<SqlDatabase>().As<IDatabase>();

            //builder.RegisterType<MySqlDatabase>().As<IDatabase>();

            _container = builder.Build();
        }

        private static void DemoAppInitContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<ConsoleOutput>().As<IOutput>();
            builder.RegisterType<TodayWriter>().As<IDateWriter>();
            _container = builder.Build();

            WriteDate();
        }

        public static void WriteDate()
        {
             /*           
                现在当运行程序时...

                "WriteDate"方法向Autofac请求一个 IDateWriter.
                Autofac发现 IDateWriter 对应 TodayWriter 因此开始创建 TodayWriter.
                Autofac发现 TodayWriter 在它构造方法中需要一个 IOutput.
                Autofac发现 IOutput 对应 ConsoleOutput 因此开始创建新的 ConsoleOutput 实例.
                Autofac使用新的 ConsoleOutput 实例完成 TodayWriter 的创建.
                Autofac返回完整构建的 TodayWriter 给"WriteDate"使用.
            */
            using (var scope = _container.BeginLifetimeScope())
            {
                var writer = scope.Resolve<IDateWriter>();
                writer.WriteDate();
                writer.WriteTom();
            }
        }
    }
}